﻿using AutoMapper;
using ERPSystem.Common.Domains.CustomerProfileCommon;
using ERPSystem.Common.Domains.Systemlogs;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using ERPSystem.Enum.OperationTypes;
using MediatR;
using SqlSugar;

namespace BasicInformationWrite.API.BasicInformationCommons.CustomerProfilees
{
    public class CustomerProfileCreateHandler : IRequestHandler<CustomerProfileCreateCommand, Result>
    {
        private readonly IBaseRepository<CustomerProfile> _customerProfileRepository;
        private readonly IBaseRepository<OperationLog> _operationLogRepository;
        private readonly IMapper _mapper;

        public CustomerProfileCreateHandler(IBaseRepository<CustomerProfile> customerProfileRepository, IBaseRepository<OperationLog> operationLogRepository, IMapper mapper)
        {
            _customerProfileRepository = customerProfileRepository;
            _operationLogRepository = operationLogRepository;
            _mapper = mapper;
        }


        /// <summary>
        /// 新增客户档案业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(CustomerProfileCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            CustomerProfile customerProfile = _mapper.Map<CustomerProfile>(request);
            try
            {
    
                var res = await _customerProfileRepository.Add(customerProfile);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
                else
                {
                    result.Msg = "添加失败";
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                await _operationLogRepository.Add(new OperationLog()
                {
                    Description = "新增客户档案基本信息，多选下拉",//描述
                    ModuleName = "客户档案",//模块名称
                    OperationType = (int)CommonErrorCode.Added,//操作类型
                    Data ="老六啊你",//数据
                    UniqueTag =customerProfile.CustomerProfileId.ToString(),//唯一标识
                });
            }
            return result;
        }
    }
}
